import os

# 设置你想要统计的文件扩展名
INCLUDE_EXT = {'.py', '.java', '.js', '.c', '.cpp', '.h', '.html', '.css', '.ts', '.vue'}

# 设置注释开头的标识符
SINGLE_LINE_COMMENT = {
    '.py': '#',
    '.java': '//',
    '.js': '//',
    '.c': '//',
    '.cpp': '//',
    '.h': '//',
    '.ts': '//',
    '.vue': '//'
}

def count_lines_in_file(file_path, ext):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
    except Exception as e:
        print(f"读取文件失败：{file_path}，错误：{e}")
        return 0

    code_lines = 0
    in_block_comment = False

    for line in lines:
        line = line.strip()

        # 处理块注释开始和结束（例如 /* ... */ ）
        if ext in ['.c', '.cpp', '.java', '.js', '.ts']:
            if '/*' in line and not in_block_comment:
                in_block_comment = True
                continue
            if '*/' in line and in_block_comment:
                in_block_comment = False
                continue
            if in_block_comment:
                continue

        if not line:
            continue  # 跳过空行

        # 单行注释跳过
        if ext in SINGLE_LINE_COMMENT and line.startswith(SINGLE_LINE_COMMENT[ext]):
            continue

        code_lines += 1

    return code_lines


def count_lines_in_dir(root_dir):
    total_lines = 0
    for root, _, files in os.walk(root_dir):
        for file in files:
            ext = os.path.splitext(file)[1]
            if ext in INCLUDE_EXT:
                file_path = os.path.join(root, file)
                lines = count_lines_in_file(file_path, ext)
                print(f"{file_path} : {lines} 行")
                total_lines += lines

    return total_lines


if __name__ == '__main__':
    path = r'C:\Users\suyujie\PycharmProjects\macro-software-python'
    # path = input("请输入你要统计的项目路径：").strip()
    if os.path.isdir(path):
        total = count_lines_in_dir(path)
        print(f"\n✅ 总代码行数（排除空行和注释）: {total} 行")
    else:
        print("❌ 输入的不是一个有效的目录")
